package com.codestation.henloserver

import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.WifiManager
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import java.io.IOException

class MainActivity : AppCompatActivity() {

    private var isStarted:Boolean = false
    private var oldIsApOnline:Boolean = false
    private var lastChangedIsByAuto:Boolean = false

    // INSTANCE OF ANDROID WEB SERVER
    private var androidWebServer:AndroidWebServer = AndroidWebServer(this, BuildConfig.defaultPort)

    private fun isApOnline(): Boolean {
        val wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        val method = wifiManager.javaClass.getDeclaredMethod("isWifiApEnabled")
        method.isAccessible = true
        return method.invoke(wifiManager) as Boolean
    }

    private fun startAndroidWebServer(): Boolean {
        if (!isStarted) {
            try {
                androidWebServer.start()
                return true
            } catch (e: IOException) {
                e.printStackTrace()
            }

        }
        return false
    }

    private fun stopAndroidWebServer(): Boolean {
        if (isStarted) {
            androidWebServer.stop()
            return true
        }
        return false
    }

    private fun changeServerStatus():Boolean {
        val oldIsStarted:Boolean = isStarted;

        if (!isStarted)
        {
            if (isApOnline()) {
                if (startAndroidWebServer())
                {
                    isStarted = true
                    val textViewIpAccess:TextView = findViewById(R.id.textViewIpAccess)
                    textViewIpAccess.text = getString(R.string.address_format, BuildConfig.defaultAddress, BuildConfig.defaultPort)
                    textViewIpAccess.visibility = View.VISIBLE
                    val textViewMessage:TextView = findViewById(R.id.textViewMessage)
                    textViewMessage.text = getString(R.string.message_running)
                    val floatingActionButtonOnOff: com.google.android.material.floatingactionbutton.FloatingActionButton = findViewById(R.id.floatingActionButtonOnOff)
                    floatingActionButtonOnOff.backgroundTintList = ContextCompat.getColorStateList(this, R.color.colorGreen)
                }
            }
        }
        else {
            if (stopAndroidWebServer())
            {
                isStarted = false
                val textViewIpAccess:TextView = findViewById(R.id.textViewIpAccess)
                textViewIpAccess.visibility = View.INVISIBLE
                val textViewMessage:TextView = findViewById(R.id.textViewMessage)
                textViewMessage.text = getString(R.string.message_stopping)
                val floatingActionButtonOnOff: com.google.android.material.floatingactionbutton.FloatingActionButton = findViewById(R.id.floatingActionButtonOnOff)
                floatingActionButtonOnOff.backgroundTintList = ContextCompat.getColorStateList(this, R.color.colorRed)
            }
        }

        return (oldIsStarted != isStarted)
    }

    private fun autoUpdateServerStatus() {
        val currentIsApOnline = isApOnline()
        if (oldIsApOnline != currentIsApOnline)
        {
            oldIsApOnline = currentIsApOnline
            if ((isStarted && !currentIsApOnline) || (!isStarted && currentIsApOnline && lastChangedIsByAuto))
            {
                changeServerStatus()
                lastChangedIsByAuto = true
            }
        }
    }

    private fun turnOnoffServer():Boolean {
        val result = changeServerStatus()
        lastChangedIsByAuto = false

        if (!result)
        {
            if (!isStarted)
            {
                val alertDialogBuilder = AlertDialog.Builder(this)
                alertDialogBuilder.setTitle(R.string.warning)
                if (!isApOnline())
                {
                    alertDialogBuilder.setMessage(R.string.dialog_message_no_ap_wifi)
                }
                else
                {
                    alertDialogBuilder.setMessage(R.string.dialog_message_failed)
                }
                alertDialogBuilder.setPositiveButton(android.R.string.ok, null)
                alertDialogBuilder.show()
            }
        }
        return result
    }

    private fun initBroadcastReceiverNetworkStateChanged() {
        val currentIsApOnline = isApOnline()
        oldIsApOnline = currentIsApOnline
        if (!isStarted && currentIsApOnline)
        {
            changeServerStatus()
        }

        val filters = IntentFilter()
        filters.addAction("android.net.wifi.WIFI_STATE_CHANGED")
        filters.addAction("android.net.wifi.STATE_CHANGE")
        filters.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED")

        val broadcastReceiverNetworkState = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                autoUpdateServerStatus()
            }
        }
        super.registerReceiver(broadcastReceiverNetworkState, filters)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val versionText:TextView = findViewById(R.id.versionText)
        versionText.text = BuildConfig.VERSION_NAME
        val textViewIpAccess:TextView = findViewById(R.id.textViewIpAccess)
        textViewIpAccess.visibility = View.INVISIBLE
        val textViewMessage:TextView = findViewById(R.id.textViewMessage)
        textViewMessage.text = getString(R.string.message_stopping)

        val buttonOnOff: com.google.android.material.floatingactionbutton.FloatingActionButton = findViewById(R.id.floatingActionButtonOnOff)
        buttonOnOff.setOnClickListener {
            turnOnoffServer()
        }

        // INIT BROADCAST RECEIVER TO LISTEN NETWORK STATE CHANGED
        initBroadcastReceiverNetworkStateChanged()
    }

    override fun onKeyDown(keyCode: Int, evt: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isStarted) {
                AlertDialog.Builder(this)
                    .setTitle(R.string.warning)
                    .setMessage(R.string.dialog_message_exit)
                    .setPositiveButton(resources.getString(android.R.string.ok)) { _, _ -> finish() }
                    .setNegativeButton(resources.getString(android.R.string.cancel), null)
                    .show()
            } else {
                finish()
            }
            return true
        }
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        stopAndroidWebServer()
        isStarted = false
    }
}
